<template>
  <div class="offers-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">Offer管理</h1>
        <p class="page-desc">管理所有发出的工作邀请，跟踪Offer状态</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreateOffer">
          <el-icon>
            <Plus />
          </el-icon>
          创建Offer
        </el-button>
        <el-button type="success" @click="handleBatchExport">
          <el-icon>
            <DocumentCopy />
          </el-icon>
          批量导出
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <div class="stat-card total">
          <div class="stat-icon">
            <el-icon>
              <Medal />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.total }}</div>
            <div class="stat-label">总Offer数</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="12" :sm="6">
        <div class="stat-card pending">
          <div class="stat-icon">
            <el-icon>
              <Clock />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.pending }}</div>
            <div class="stat-label">待回复</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="12" :sm="6">
        <div class="stat-card accepted">
          <div class="stat-icon">
            <el-icon>
              <Check />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.accepted }}</div>
            <div class="stat-label">已接受</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="12" :sm="6">
        <div class="stat-card rejected">
          <div class="stat-icon">
            <el-icon>
              <Close />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.rejected }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="候选人姓名">
          <el-input v-model="searchForm.candidateName" placeholder="请输入候选人姓名" clearable style="width: 150px" />
        </el-form-item>

        <el-form-item label="职位">
          <el-select v-model="searchForm.jobId" placeholder="请选择职位" clearable filterable style="width: 200px">
            <el-option v-for="job in jobList" :key="job.id" :label="job.title" :value="job.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="Offer状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="待发送" value="draft" />
            <el-option label="已发送" value="sent" />
            <el-option label="已查看" value="viewed" />
            <el-option label="已接受" value="accepted" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已过期" value="expired" />
            <el-option label="已撤回" value="withdrawn" />
          </el-select>
        </el-form-item>

        <el-form-item label="薪资范围">
          <el-input v-model="searchForm.salaryMin" placeholder="最低薪资" style="width: 100px" />
          <span style="margin: 0 8px">-</span>
          <el-input v-model="searchForm.salaryMax" placeholder="最高薪资" style="width: 100px" />
        </el-form-item>

        <el-form-item label="发送时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 240px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Offer列表 -->
    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="Offer ID" width="100" />

        <!-- 候选人信息 -->
        <el-table-column label="候选人信息" min-width="200">
          <template #default="{ row }">
            <div class="candidate-info">
              <el-avatar :size="40" :src="row.candidateAvatar">
                <el-icon>
                  <User />
                </el-icon>
              </el-avatar>
              <div class="info-content">
                <div class="candidate-name">{{ row.candidateName }}</div>
                <div class="candidate-contact">
                  <span>{{ row.candidatePhone }}</span>
                  <span class="email">{{ row.candidateEmail }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 职位信息 -->
        <el-table-column label="职位信息" min-width="150">
          <template #default="{ row }">
            <div class="job-info">
              <div class="job-title">{{ row.jobTitle }}</div>
              <div class="job-department">{{ row.department }}</div>
            </div>
          </template>
        </el-table-column>

        <!-- 薪资信息 -->
        <el-table-column label="薪资信息" min-width="120">
          <template #default="{ row }">
            <div class="salary-info">
              <div class="base-salary">基本薪资：{{ row.baseSalary }}</div>
              <div class="total-package">总包：{{ row.totalPackage }}</div>
            </div>
          </template>
        </el-table-column>

        <!-- Offer状态 -->
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 有效期 -->
        <el-table-column label="有效期" width="120">
          <template #default="{ row }">
            <div class="validity-info">
              <div class="expire-date">{{ formatDate(row.expireDate) }}</div>
              <div class="days-left" :class="getDaysLeftClass(row.expireDate)">
                {{ getDaysLeft(row.expireDate) }}
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 发送时间 -->
        <el-table-column label="发送时间" width="180">
          <template #default="{ row }">
            {{ row.sentAt ? formatDate(row.sentAt) : '-' }}
          </template>
        </el-table-column>

        <!-- 回复时间 -->
        <el-table-column label="回复时间" width="180">
          <template #default="{ row }">
            {{ row.respondedAt ? formatDate(row.respondedAt) : '-' }}
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewOffer(row)">
              <el-icon>
                <View />
              </el-icon>
              查看
            </el-button>
            <el-button v-if="row.status === 'draft'" type="success" link @click="handleSendOffer(row)">
              <el-icon>
                <Promotion />
              </el-icon>
              发送
            </el-button>
            <el-button v-if="['draft', 'sent'].includes(row.status)" type="primary" link @click="handleEditOffer(row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleAction(command, row)">
              <el-button type="primary" link>
                更多
                <el-icon>
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="duplicate">
                    <el-icon>
                      <DocumentCopy />
                    </el-icon>
                    复制
                  </el-dropdown-item>
                  <el-dropdown-item command="withdraw" v-if="['sent', 'viewed'].includes(row.status)">
                    <el-icon>
                      <RefreshLeft />
                    </el-icon>
                    撤回
                  </el-dropdown-item>
                  <el-dropdown-item command="remind" v-if="['sent', 'viewed'].includes(row.status)">
                    <el-icon>
                      <Bell />
                    </el-icon>
                    提醒
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <el-icon>
                      <Delete />
                    </el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 创建/编辑Offer对话框 -->
    <el-dialog v-model="offerDialogVisible" :title="dialogTitle" width="800px" @close="handleOfferDialogClose">
      <el-form ref="offerFormRef" :model="offerForm" :rules="offerRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="候选人" prop="candidateId">
              <el-select v-model="offerForm.candidateId" placeholder="请选择候选人" filterable style="width: 100%"
                @change="handleCandidateChange">
                <el-option v-for="candidate in candidateList" :key="candidate.id" :label="candidate.name"
                  :value="candidate.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="jobId">
              <el-select v-model="offerForm.jobId" placeholder="请选择职位" filterable style="width: 100%">
                <el-option v-for="job in jobList" :key="job.id" :label="job.title" :value="job.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="基本薪资" prop="baseSalary">
              <el-input-number v-model="offerForm.baseSalary" :min="0" :step="1000" style="width: 100%"
                placeholder="请输入基本薪资" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绩效奖金" prop="performanceBonus">
              <el-input-number v-model="offerForm.performanceBonus" :min="0" :step="1000" style="width: 100%"
                placeholder="请输入绩效奖金" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="股票期权" prop="stockOptions">
              <el-input-number v-model="offerForm.stockOptions" :min="0" :step="1000" style="width: 100%"
                placeholder="请输入股票期权" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他福利" prop="otherBenefits">
              <el-input-number v-model="offerForm.otherBenefits" :min="0" :step="1000" style="width: 100%"
                placeholder="请输入其他福利" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职日期" prop="startDate">
              <el-date-picker v-model="offerForm.startDate" type="date" placeholder="请选择入职日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Offer有效期" prop="expireDate">
              <el-date-picker v-model="offerForm.expireDate" type="date" placeholder="请选择有效期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="工作地点" prop="workLocation">
          <el-input v-model="offerForm.workLocation" placeholder="请输入工作地点" />
        </el-form-item>

        <el-form-item label="福利待遇" prop="benefits">
          <el-checkbox-group v-model="offerForm.benefits">
            <el-checkbox label="五险一金">五险一金</el-checkbox>
            <el-checkbox label="带薪年假">带薪年假</el-checkbox>
            <el-checkbox label="弹性工作">弹性工作</el-checkbox>
            <el-checkbox label="免费午餐">免费午餐</el-checkbox>
            <el-checkbox label="健身房">健身房</el-checkbox>
            <el-checkbox label="培训机会">培训机会</el-checkbox>
            <el-checkbox label="团建活动">团建活动</el-checkbox>
            <el-checkbox label="节日福利">节日福利</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="备注说明" prop="remarks">
          <el-input v-model="offerForm.remarks" type="textarea" :rows="4" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="offerDialogVisible = false">取消</el-button>
          <el-button @click="handleSaveDraft" :loading="saving">
            保存草稿
          </el-button>
          <el-button type="primary" @click="handleSaveAndSend" :loading="saving">
            保存并发送
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Offer详情对话框 -->
    <el-dialog v-model="offerDetailVisible" title="Offer详情" width="70%" top="5vh">
      <div v-if="currentOffer" class="offer-detail">
        <!-- Offer基本信息 -->
        <div class="offer-header">
          <div class="header-left">
            <h2>{{ currentOffer.candidateName }} - {{ currentOffer.jobTitle }}</h2>
            <div class="offer-meta">
              <el-tag :type="getStatusTagType(currentOffer.status)">
                {{ getStatusText(currentOffer.status) }}
              </el-tag>
              <span class="offer-id">Offer ID: {{ currentOffer.id }}</span>
            </div>
          </div>
          <div class="header-right">
            <el-button v-if="currentOffer.status === 'draft'" type="primary" @click="handleSendOffer(currentOffer)">
              <el-icon>
                <Promotion />
              </el-icon>
              发送Offer
            </el-button>
            <el-button @click="handlePrintOffer">
              <el-icon>
                <Printer />
              </el-icon>
              打印
            </el-button>
          </div>
        </div>

        <!-- Offer内容 -->
        <el-tabs v-model="activeDetailTab" class="offer-tabs">
          <el-tab-pane label="薪资待遇" name="salary">
            <div class="offer-section">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="基本薪资">{{ currentOffer.baseSalary }} 元/月</el-descriptions-item>
                <el-descriptions-item label="绩效奖金">{{ currentOffer.performanceBonus || 0 }} 元/月</el-descriptions-item>
                <el-descriptions-item label="股票期权">{{ currentOffer.stockOptions || 0 }} 元</el-descriptions-item>
                <el-descriptions-item label="其他福利">{{ currentOffer.otherBenefits || 0 }} 元</el-descriptions-item>
                <el-descriptions-item label="年薪总包">
                  <span class="total-package">{{ calculateTotalPackage(currentOffer) }} 元</span>
                </el-descriptions-item>
                <el-descriptions-item label="入职日期">{{ formatDate(currentOffer.startDate) }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>

          <el-tab-pane label="工作信息" name="job">
            <div class="offer-section">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="职位名称">{{ currentOffer.jobTitle }}</el-descriptions-item>
                <el-descriptions-item label="所属部门">{{ currentOffer.department }}</el-descriptions-item>
                <el-descriptions-item label="工作地点">{{ currentOffer.workLocation }}</el-descriptions-item>
                <el-descriptions-item label="汇报对象">{{ currentOffer.reportTo || '待定' }}</el-descriptions-item>
                <el-descriptions-item label="工作性质">{{ currentOffer.jobType || '全职' }}</el-descriptions-item>
                <el-descriptions-item label="试用期">{{ currentOffer.probationPeriod || '3个月' }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>

          <el-tab-pane label="福利待遇" name="benefits">
            <div class="offer-section">
              <h3>福利项目</h3>
              <div class="benefits-list">
                <el-tag v-for="benefit in currentOffer.benefits" :key="benefit" class="benefit-tag">
                  {{ benefit }}
                </el-tag>
              </div>

              <h3 style="margin-top: 20px">备注说明</h3>
              <p class="remarks">{{ currentOffer.remarks || '无' }}</p>
            </div>
          </el-tab-pane>

          <el-tab-pane label="状态记录" name="history">
            <div class="offer-section">
              <el-timeline>
                <el-timeline-item v-for="record in currentOffer.statusHistory" :key="record.id"
                  :timestamp="formatDate(record.createdAt)" :type="getTimelineType(record.status)">
                  <div class="timeline-content">
                    <h4>{{ getStatusText(record.status) }}</h4>
                    <p>{{ record.description }}</p>
                    <span class="operator">操作人：{{ record.operator }}</span>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  DocumentCopy,
  Medal,
  Clock,
  Check,
  Close,
  Search,
  Refresh,
  User,
  View,
  Promotion,
  Edit,
  ArrowDown,
  RefreshLeft,
  Bell,
  Delete,
  Printer
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const offerDialogVisible = ref(false)
const offerDetailVisible = ref(false)
const isEdit = ref(false)
const offerFormRef = ref()
const currentOffer = ref(null)
const activeDetailTab = ref('salary')
const selectedOffers = ref([])

// 统计数据
const stats = ref({
  total: 45,
  pending: 12,
  accepted: 23,
  rejected: 8
})

// 搜索表单
const searchForm = reactive({
  candidateName: '',
  jobId: null,
  status: '',
  salaryMin: '',
  salaryMax: '',
  dateRange: null
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 职位列表
const jobList = ref([
  { id: 1, title: 'Java开发工程师' },
  { id: 2, title: '前端开发工程师' },
  { id: 3, title: '产品经理' },
  { id: 4, title: 'UI设计师' }
])

// 候选人列表
const candidateList = ref([
  { id: 1, name: '张小明', phone: '13800138001', email: 'zhangxiaoming@email.com' },
  { id: 2, name: '李小红', phone: '13800138002', email: 'lixiaohong@email.com' },
  { id: 3, name: '王小强', phone: '13800138003', email: 'wangxiaoqiang@email.com' }
])

// Offer数据
const tableData = ref([
  {
    id: 'OF001',
    candidateId: 1,
    candidateName: '张小明',
    candidatePhone: '13800138001',
    candidateEmail: 'zhangxiaoming@email.com',
    candidateAvatar: '',
    jobId: 1,
    jobTitle: 'Java开发工程师',
    department: '技术部',
    baseSalary: 18000,
    performanceBonus: 3000,
    stockOptions: 10000,
    otherBenefits: 2000,
    totalPackage: 396000,
    startDate: '2024-03-01',
    expireDate: '2024-02-15',
    workLocation: '北京市朝阳区',
    benefits: ['五险一金', '带薪年假', '弹性工作', '免费午餐'],
    remarks: '优秀候选人，技术能力强',
    status: 'sent',
    sentAt: '2024-01-20T10:30:00',
    respondedAt: null,
    statusHistory: [
      {
        id: 1,
        status: 'draft',
        description: 'Offer创建完成',
        operator: '李小红',
        createdAt: '2024-01-20T09:00:00'
      },
      {
        id: 2,
        status: 'sent',
        description: 'Offer已发送给候选人',
        operator: '李小红',
        createdAt: '2024-01-20T10:30:00'
      }
    ]
  },
  {
    id: 'OF002',
    candidateId: 2,
    candidateName: '李小红',
    candidatePhone: '13800138002',
    candidateEmail: 'lixiaohong@email.com',
    candidateAvatar: '',
    jobId: 2,
    jobTitle: '前端开发工程师',
    department: '技术部',
    baseSalary: 15000,
    performanceBonus: 2000,
    stockOptions: 8000,
    otherBenefits: 1500,
    totalPackage: 318000,
    startDate: '2024-02-20',
    expireDate: '2024-02-10',
    workLocation: '上海市浦东新区',
    benefits: ['五险一金', '带薪年假', '健身房'],
    remarks: '前端技术扎实，有良好的设计感',
    status: 'accepted',
    sentAt: '2024-01-18T14:20:00',
    respondedAt: '2024-01-19T16:30:00',
    statusHistory: [
      {
        id: 1,
        status: 'draft',
        description: 'Offer创建完成',
        operator: '王小明',
        createdAt: '2024-01-18T13:00:00'
      },
      {
        id: 2,
        status: 'sent',
        description: 'Offer已发送给候选人',
        operator: '王小明',
        createdAt: '2024-01-18T14:20:00'
      },
      {
        id: 3,
        status: 'accepted',
        description: '候选人已接受Offer',
        operator: '系统',
        createdAt: '2024-01-19T16:30:00'
      }
    ]
  }
])

// Offer表单
const offerForm = reactive({
  id: null,
  candidateId: null,
  jobId: null,
  baseSalary: null,
  performanceBonus: null,
  stockOptions: null,
  otherBenefits: null,
  startDate: '',
  expireDate: '',
  workLocation: '',
  benefits: [],
  remarks: ''
})

// 表单验证规则
const offerRules = {
  candidateId: [
    { required: true, message: '请选择候选人', trigger: 'change' }
  ],
  jobId: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ],
  baseSalary: [
    { required: true, message: '请输入基本薪资', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  expireDate: [
    { required: true, message: '请选择Offer有效期', trigger: 'change' }
  ],
  workLocation: [
    { required: true, message: '请输入工作地点', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑Offer' : '创建Offer')

// 方法定义

/**
 * 获取状态标签类型
 */
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'draft': 'info',
    'sent': 'warning',
    'viewed': 'primary',
    'accepted': 'success',
    'rejected': 'danger',
    'expired': 'danger',
    'withdrawn': 'info'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态文本
 */
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'draft': '待发送',
    'sent': '已发送',
    'viewed': '已查看',
    'accepted': '已接受',
    'rejected': '已拒绝',
    'expired': '已过期',
    'withdrawn': '已撤回'
  }
  return textMap[status] || status
}

/**
 * 获取时间线类型
 */
const getTimelineType = (status: string) => {
  const typeMap: Record<string, string> = {
    'draft': 'primary',
    'sent': 'warning',
    'viewed': 'primary',
    'accepted': 'success',
    'rejected': 'danger',
    'expired': 'danger',
    'withdrawn': 'info'
  }
  return typeMap[status] || 'primary'
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

/**
 * 获取剩余天数
 */
const getDaysLeft = (expireDate: string) => {
  const expire = new Date(expireDate)
  const now = new Date()
  const diffTime = expire.getTime() - now.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays < 0) {
    return '已过期'
  } else if (diffDays === 0) {
    return '今日到期'
  } else {
    return `${diffDays}天后到期`
  }
}

/**
 * 获取剩余天数样式类
 */
const getDaysLeftClass = (expireDate: string) => {
  const expire = new Date(expireDate)
  const now = new Date()
  const diffTime = expire.getTime() - now.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays < 0) {
    return 'expired'
  } else if (diffDays <= 3) {
    return 'urgent'
  } else {
    return 'normal'
  }
}

/**
 * 计算总薪资包
 */
const calculateTotalPackage = (offer: any) => {
  const base = offer.baseSalary || 0
  const bonus = offer.performanceBonus || 0
  const stock = offer.stockOptions || 0
  const other = offer.otherBenefits || 0

  return (base + bonus) * 12 + stock + other
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    candidateName: '',
    jobId: null,
    status: '',
    salaryMin: '',
    salaryMax: '',
    dateRange: null
  })
  handleSearch()
}

/**
 * 创建Offer
 */
const handleCreateOffer = () => {
  isEdit.value = false
  resetOfferForm()
  offerDialogVisible.value = true
}

/**
 * 查看Offer
 */
const handleViewOffer = (offer: any) => {
  currentOffer.value = offer
  offerDetailVisible.value = true
  activeDetailTab.value = 'salary'
}

/**
 * 编辑Offer
 */
const handleEditOffer = (offer: any) => {
  isEdit.value = true
  Object.assign(offerForm, {
    id: offer.id,
    candidateId: offer.candidateId,
    jobId: offer.jobId,
    baseSalary: offer.baseSalary,
    performanceBonus: offer.performanceBonus,
    stockOptions: offer.stockOptions,
    otherBenefits: offer.otherBenefits,
    startDate: offer.startDate,
    expireDate: offer.expireDate,
    workLocation: offer.workLocation,
    benefits: [...offer.benefits],
    remarks: offer.remarks
  })
  offerDialogVisible.value = true
}

/**
 * 发送Offer
 */
const handleSendOffer = (offer: any) => {
  ElMessageBox.confirm(
    `确定要发送Offer给「${offer.candidateName}」吗？`,
    '发送确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    offer.status = 'sent'
    offer.sentAt = new Date().toISOString()
    ElMessage.success('Offer发送成功')
    // TODO: 调用API发送Offer
  })
}

/**
 * 候选人改变
 */
const handleCandidateChange = (candidateId: number) => {
  const candidate = candidateList.value.find(c => c.id === candidateId)
  if (candidate) {
    // 可以根据候选人信息自动填充一些字段
  }
}

/**
 * 处理操作
 */
const handleAction = (command: string, offer: any) => {
  switch (command) {
    case 'duplicate':
      handleDuplicateOffer(offer)
      break
    case 'withdraw':
      handleWithdrawOffer(offer)
      break
    case 'remind':
      handleRemindCandidate(offer)
      break
    case 'delete':
      handleDeleteOffer(offer)
      break
  }
}

/**
 * 复制Offer
 */
const handleDuplicateOffer = (offer: any) => {
  isEdit.value = false
  Object.assign(offerForm, {
    id: null,
    candidateId: null,
    jobId: offer.jobId,
    baseSalary: offer.baseSalary,
    performanceBonus: offer.performanceBonus,
    stockOptions: offer.stockOptions,
    otherBenefits: offer.otherBenefits,
    startDate: '',
    expireDate: '',
    workLocation: offer.workLocation,
    benefits: [...offer.benefits],
    remarks: offer.remarks
  })
  offerDialogVisible.value = true
}

/**
 * 撤回Offer
 */
const handleWithdrawOffer = (offer: any) => {
  ElMessageBox.confirm(
    `确定要撤回发送给「${offer.candidateName}」的Offer吗？`,
    '撤回确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    offer.status = 'withdrawn'
    ElMessage.success('Offer撤回成功')
    // TODO: 调用API撤回Offer
  })
}

/**
 * 提醒候选人
 */
const handleRemindCandidate = (offer: any) => {
  ElMessage.success(`已发送提醒给 ${offer.candidateName}`)
  // TODO: 调用API发送提醒
}

/**
 * 删除Offer
 */
const handleDeleteOffer = (offer: any) => {
  ElMessageBox.confirm(
    `确定要删除发送给「${offer.candidateName}」的Offer吗？此操作不可恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    const index = tableData.value.findIndex(item => item.id === offer.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
    ElMessage.success('Offer删除成功')
    // TODO: 调用API删除Offer
  })
}

/**
 * 批量导出
 */
const handleBatchExport = () => {
  ElMessage.info('批量导出功能开发中')
  // TODO: 实现批量导出功能
}

/**
 * 打印Offer
 */
const handlePrintOffer = () => {
  ElMessage.info('打印功能开发中')
  // TODO: 实现打印功能
}

/**
 * 保存草稿
 */
const handleSaveDraft = async () => {
  try {
    await offerFormRef.value.validate()
    saving.value = true

    // TODO: 调用API保存草稿
    setTimeout(() => {
      saving.value = false
      offerDialogVisible.value = false
      ElMessage.success('草稿保存成功')
      loadData()
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 保存并发送
 */
const handleSaveAndSend = async () => {
  try {
    await offerFormRef.value.validate()
    saving.value = true

    // TODO: 调用API保存并发送
    setTimeout(() => {
      saving.value = false
      offerDialogVisible.value = false
      ElMessage.success('Offer发送成功')
      loadData()
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 选择改变
 */
const handleSelectionChange = (selection: any[]) => {
  selectedOffers.value = selection
}

/**
 * Offer对话框关闭
 */
const handleOfferDialogClose = () => {
  resetOfferForm()
}

/**
 * 重置Offer表单
 */
const resetOfferForm = () => {
  Object.assign(offerForm, {
    id: null,
    candidateId: null,
    jobId: null,
    baseSalary: null,
    performanceBonus: null,
    stockOptions: null,
    otherBenefits: null,
    startDate: '',
    expireDate: '',
    workLocation: '',
    benefits: [],
    remarks: ''
  })
  offerFormRef.value?.clearValidate()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  loadData()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

/**
 * 加载数据
 */
const loadData = () => {
  loading.value = true
  // TODO: 调用API获取数据
  setTimeout(() => {
    pagination.total = 45
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.offers-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
}

.page-desc {
  color: #909399;
  margin: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  border-left: 4px solid;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card.total {
  border-left-color: #409eff;
}

.stat-card.pending {
  border-left-color: #e6a23c;
}

.stat-card.accepted {
  border-left-color: #67c23a;
}

.stat-card.rejected {
  border-left-color: #f56c6c;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.total .stat-icon {
  background: #409eff;
}

.pending .stat-icon {
  background: #e6a23c;
}

.accepted .stat-icon {
  background: #67c23a;
}

.rejected .stat-icon {
  background: #f56c6c;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
}

.candidate-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-content {
  flex: 1;
}

.candidate-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.candidate-contact {
  font-size: 12px;
  color: #909399;
}

.candidate-contact .email {
  margin-left: 8px;
}

.job-info {
  line-height: 1.5;
}

.job-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.job-department {
  font-size: 12px;
  color: #909399;
}

.salary-info {
  line-height: 1.5;
  font-size: 14px;
}

.base-salary {
  color: #303133;
  margin-bottom: 2px;
}

.total-package {
  color: #f56c6c;
  font-weight: 500;
}

.validity-info {
  line-height: 1.5;
  font-size: 14px;
}

.expire-date {
  color: #303133;
  margin-bottom: 2px;
}

.days-left {
  font-size: 12px;
}

.days-left.normal {
  color: #67c23a;
}

.days-left.urgent {
  color: #e6a23c;
}

.days-left.expired {
  color: #f56c6c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.offer-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.offer-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #303133;
}

.offer-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.offer-id {
  color: #666;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 8px;
}

.offer-tabs {
  margin-top: 20px;
}

.offer-section {
  padding: 20px 0;
}

.offer-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
}

.benefits-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.benefit-tag {
  margin: 0;
}

.remarks {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  line-height: 1.6;
  color: #666;
  margin: 0;
}

.timeline-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #303133;
}

.timeline-content p {
  margin: 0 0 4px 0;
  color: #666;
  font-size: 13px;
}

.operator {
  font-size: 12px;
  color: #999;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .header-right {
    align-self: stretch;
    justify-content: space-between;
  }

  .stats-row .el-col {
    margin-bottom: 12px;
  }

  .offer-header {
    flex-direction: column;
    gap: 16px;
  }

  .header-right {
    align-self: stretch;
    justify-content: center;
  }
}
</style>
